package com.tangtang.mvc.controller;

import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.tangtang.core.basic.Action;
import com.tangtang.core.tree.Tree;
import com.tangtang.core.tree.TreeVisitor;
import com.tangtang.security.MyUserDetails;
import com.tangtang.security.service.UserService;
import com.tangtang.security.view.model.SysViewResource;

@Controller
public class IndexController extends BaseController
{
	@Autowired
	UserService	service;
	
	@RequestMapping(value = "/index.do")
	public ModelAndView index()
	{
		final String rurl = super.request.getServletPath();
		ModelAndView mav = new ModelAndView("index");
		mav.addObject("requesturl", rurl);
		return mav;
	}
	
	@RequestMapping(value = "/menu.do")
	public ModelAndView menu(String url) throws IOException
	{
		//response.getWriter().write(request.getSession().getServletContext().getRealPath("/"));
		ModelAndView mav = new ModelAndView("menu");
		MyUserDetails userDetails = (MyUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		List<Tree<SysViewResource>> menusList = service.getMenusTreeByUserId(userDetails.getUserId());
		if (menusList != null && menusList.size() > 0)
		{
			final String rurl = url;
			
			Action<Tree<SysViewResource>> action = new Action<Tree<SysViewResource>>()
			{
				@Override
				public void apply(Tree<SysViewResource> input)
				{
					if (input.getValue().getResourceUrl().equals(rurl))
					{
						input.getValue().setActive(true);
						while (input.getParent() != null)
						{
							input.getParent().getValue().setActive(true);
							input = input.getParent();
						}
					}
				}
			};
			for (int i = 0; i < menusList.size(); i++)
			{
				Tree<SysViewResource> tree = menusList.get(i);
				if (i == 0)
				{
					tree.getValue().setFirst(true);
				}
				else if (i == menusList.size())
				{
					tree.getValue().setLast(true);
				}
				TreeVisitor.visit(tree, action);
			}
		}
		mav.addObject("menus", menusList);
		return mav;
	}
}
